<template>
  <div class="register-container">
    <!-- 标题区域 -->
    <div class="register-header">
      <h1>电影售票系统</h1>
      <p>请填写信息注册新账户</p>
    </div>

    <!-- 表单区域 -->
    <form class="register-form" @submit.prevent="handleRegister">
      <!-- 用户名 -->
      <div class="form-group">
        <label for="reg-username">用户名</label>
        <input
          type="text"
          id="reg-username"
          v-model="username"
          placeholder="请设置用户名"
          required
        />
        <span class="error-message" v-if="errors.username">{{
          errors.username
        }}</span>
      </div>

      <!-- 手机号 -->
      <div class="form-group">
        <label for="reg-phone">手机号</label>
        <input
          type="tel"
          id="reg-phone"
          v-model="phone"
          placeholder="请输入11位手机号码"
          required
          pattern="[0-9]{11}"
        />
        <span class="error-message" v-if="errors.phone">{{
          errors.phone
        }}</span>
      </div>

      <!-- 密码 -->
      <div class="form-group">
        <label for="reg-password">密码</label>
        <input
          type="password"
          id="reg-password"
          v-model="password"
          placeholder="请设置6-16位密码"
          required
        />
        <span class="error-message" v-if="errors.password">{{
          errors.password
        }}</span>
      </div>

      <!-- 确认密码 -->
      <div class="form-group">
        <label for="reg-confirm">确认密码</label>
        <input
          type="password"
          id="reg-confirm"
          v-model="confirmPassword"
          placeholder="请再次输入密码"
          required
        />
        <span class="error-message" v-if="errors.confirmPassword">{{
          errors.confirmPassword
        }}</span>
      </div>

      <!-- 注册按钮 -->
      <button type="submit" class="register-btn" :disabled="isSubmitting">
        {{ isSubmitting ? "注册中..." : "注册" }}
      </button>

      <!-- 切换登录链接 -->
      <div class="register-actions">
        <span>已有账号？</span>
        <RouterLink to="/login" class="login-link">立即登录</RouterLink>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { register } from "@/api/user";
import { RouterLink } from "vue-router";

// 表单数据
const phone = ref("");
const username = ref("");
const password = ref("");
const confirmPassword = ref("");

// 状态管理
const errors = reactive({});
const isSubmitting = ref(false);
const router = useRouter();

// 表单验证
const validateForm = () => {
  let isValid = true;
  errors.username = "";
  errors.phone = "";
  errors.password = "";
  errors.confirmPassword = "";

  // 用户名验证
  if (!username.value) {
    errors.username = "请输入用户名";
    isValid = false;
  } else if (username.value.length < 2 || username.value.length > 16) {
    errors.username = "用户名长度应为2-16位";
    isValid = false;
  }

  // 手机号验证
  if (!phone.value) {
    errors.phone = "请输入手机号";
    isValid = false;
  } else if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    errors.phone = "请输入正确的11位手机号";
    isValid = false;
  }

  // 密码验证
  if (!password.value) {
    errors.password = "请输入密码";
    isValid = false;
  } else if (password.value.length < 6 || password.value.length > 16) {
    errors.password = "密码长度应为6-16位";
    isValid = false;
  }

  // 确认密码验证
  if (!confirmPassword.value) {
    errors.confirmPassword = "请确认密码";
    isValid = false;
  } else if (confirmPassword.value !== password.value) {
    errors.confirmPassword = "两次输入的密码不一致";
    isValid = false;
  }

  return isValid;
};

// 处理注册（适配后端新响应格式）
const handleRegister = async () => {
  if (!validateForm()) return;

  try {
    isSubmitting.value = true;
    const res = await register({
      phone: phone.value,
      username: username.value,
      password: password.value,
    });

    // 后端用 code=200 表示成功（与登录接口保持一致）
    if (res.data.code === 200) {
      alert(res.data.message || "注册成功，请登录");
      router.push("/login");
    } else {
      // 非200状态显示后端返回的错误信息
      alert(res.data.message || "注册失败，请重试");
    }
  } catch (err) {
    console.error("注册失败", err);
    // 错误信息容错处理（兼容网络错误或后端异常）
    const errorMsg = err.response?.data?.message || "网络错误，注册失败";
    alert(errorMsg);
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
/* 整体容器：居中布局 + 留白 */
.register-container {
  max-width: 400px;
  margin: 50px auto; /* 上下留白50px，水平居中 */
  padding: 0 20px;
}

/* 标题区域：与表单区明确分隔 */
.register-header {
  text-align: center;
  margin-bottom: 40px; /* 与表单保持距离 */
}

.register-header h1 {
  color: #a2131d; /* 主色调统一 */
  font-size: 28px;
  margin-bottom: 10px;
}

.register-header p {
  color: #666;
  font-size: 15px;
}

/* 表单容器：内部间距控制 */
.register-form {
  width: 100%;
}

/* 表单项：统一间距 */
.form-group {
  margin-bottom: 22px; /* 表单项之间的垂直间距 */
}

.form-group label {
  display: block;
  margin-bottom: 8px; /* label与输入框的距离 */
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 12px 15px; /* 输入框内边距，增加点击区域 */
  border: 1px solid #ddd;
  border-radius: 4px; /* 与登录页统一圆角 */
  font-size: 15px;
  transition: all 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #a2131d; /* 聚焦时主色调高亮 */
  box-shadow: 0 0 0 2px rgba(162, 19, 29, 0.1); /* 轻微发光效果 */
}

/* 注册按钮：强调视觉 */
.register-btn {
  width: 100%;
  padding: 12px;
  background-color: #a2131d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin: 10px 0 30px; /* 上下留白，与其他元素分隔 */
  transition: all 0.2s;
}

.register-btn:hover:not(:disabled) {
  background-color: #8a1018; /* 深色反馈 */
  transform: translateY(-2px); /* 轻微上浮 */
  box-shadow: 0 4px 8px rgba(162, 19, 29, 0.2); /* 增加立体感 */
}

.register-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 底部链接区域：居中布局 */
.register-actions {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.login-link {
  color: #a2131d;
  text-decoration: none;
  margin-left: 5px;
  transition: color 0.2s;
}

.login-link:hover {
  color: #8a1018;
}

/* 错误提示：统一样式 */
.error-message {
  color: #a2131d;
  font-size: 12px;
  margin-top: 5px;
  display: block;
  min-height: 18px; /* 防止表单高度跳动 */
}

/* 响应式适配：小屏幕优化 */
@media (max-width: 768px) {
  .register-container {
    margin: 30px auto;
  }

  .register-header {
    margin-bottom: 30px;
  }
}
</style>
